package com.twq.types.typeparam.covariant

/**
 * Created by tangweiqun on 2017/12/6.
 * 下界
 */
class Queue[+T](elems: List[T]) {

  def head: T = elems.head

  def tail: Queue[T] = new Queue(elems.tail)

  //U必须是T类型或者是T类型的父类， T 就是下界
  def enqueue[U >: T](x: U) = new Queue(elems ::: List(x))

  override def toString: String = elems.mkString
}

//class StrangeIntQueue extends Queue[Int](Nil) {
//    override def enqueue(x: Int) = {
//      println(math.sqrt(x))
//      super.enqueue(x)
//    }
//  }

object Queue {
  def main(args: Array[String]): Unit = {
    //1、协变使得运行时类型设置不对
    //val x: Queue[Any] = new StrangeIntQueue
    //x.enqueue("abc")

    //
    val queue = new Queue[Apple](List(new Apple))
    val q1 = queue.enqueue(new Apple) //Queue[Apple]
    println(q1)
    val q2 = queue.enqueue(new Fruit) //Queue[Fruit]
    println(q2)

    val q3 = queue.enqueue(new Orange) //Queue[Fruit]
    println(q3)

  }
}


class Fruit

class Apple extends Fruit

class Orange extends Fruit


